﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.Model;
using System.Data;
using HZ.DrugTrade.Model.Enum;

namespace HZ.DrugTrade.Web.Enterprise.RelationQuery
{
    public partial class DistributionRelationWithWizard : BasePage
    {
        public DistributionRelationWithWizard()
        {
            //this.ModuleNo = Module.可配送区域管理.ToString();
        }

        IBLL_Area iArea = Factory.BLL_Area();
        IBLL_SelectArea iSelectArea = Factory.BLL_SelectArea();
        IBLL_SelectRelation iSelectRelation = Factory.BLL_SelectRelation();
        IBLL_Company iCompany = Factory.BLL_Company();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (string.IsNullOrEmpty(HZ.Fun2.CheckString(Request.QueryString["PID"])))
                {
                    PageError("非法路径！", "");
                }
                else
                {

                    setBind();
                }
                BangdinGvRelaion();
            }
        }


        /// <summary>
        /// 绑定所有符合条件的采购目录
        /// </summary>
        private void setBind()
        {
            ViewState["ishcygcg"] = Request.QueryString["ishcygcg"];
            ViewState["ProjectId"] = Request.QueryString["ProjectId"];
            string CompanyID_PS = HZ.Fun2.CheckString(Request.QueryString["PID"]);
            //配送企业名称
            CompanyInfo comInfo=iCompany.GetCompanyInfoByID(CompanyID_PS);
            this.lblCompanyName.Text= comInfo.CompanyName;

            Model.Area aArea = CurrentAccount.GetCurrentDeployArea();  //获取当前实施地区的地区

            IList<Model.Area> aAreaList = iArea.GetAllCity(aArea.AreaID);
            gvwArea.DataSource = aAreaList;
            gvwArea.DataBind();

            //IList<Model.SelectArea> sSelectAreaList = iSelectArea.GetAllCity(CompanyID_PS);

            string areaIds = HZ.DrugTrade.BLLFactory.Factory.BLL_Area().GetNeedCity(CompanyID_PS, ViewState["ProjectId"].ToString());
            //20091227注释 减少配送关系的查询
            IList<Model.SelectRelation> sSelectRelationList = iSelectRelation.GetAllSelectRelationByCompanyPSID(CompanyID_PS);

            string strPSAreas = ",";
            foreach (Model.SelectRelation item in sSelectRelationList)
            {
                if (strPSAreas.Contains(item.AreaID) == false)
                {
                    strPSAreas += item.AreaID + ",";
                }
            }
            if (areaIds!="")
            {
                for (int _index = 0; _index < gvwArea.Rows.Count; _index++)
                {
                    CheckBox ckb = (CheckBox)gvwArea.Rows[_index].FindControl("checkbox1");
                    if (areaIds.Contains(this.gvwArea.DataKeys[_index].Value.ToString().ToUpper()))
                    {
                        if (strPSAreas.Contains(this.gvwArea.DataKeys[_index].Value.ToString().ToUpper()))
                        {
                            ckb.Checked = true;
                            //ckb.Enabled = false;
                        }
                    }
                    else
                    {
                        ckb.Enabled = false;
                    }
                }
            }
            else
            {
                for (int _index = 0; _index < gvwArea.Rows.Count; _index++)
                {
                    CheckBox ckb = (CheckBox)gvwArea.Rows[_index].FindControl("checkbox1");

                    ckb.Enabled = false;
                }
            }
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
        }
        /// <summary>
        /// 绑定事件
        /// </summary>
        private void BangdinGvRelaion()
        {
            HZ.DrugTrade.Model.Query.ProcureCatalog procureCatalog = new HZ.DrugTrade.Model.Query.ProcureCatalog();
            procureCatalog.CompanyID_TB = CurrentAccount.GetUser().Org.OrgID;
            procureCatalog.Outlookc = txtOutlookc.Text.Trim();
            procureCatalog.Material = txtMaterial.Text.Trim();
            procureCatalog.Unit = txtUnit.Text.Trim();
            procureCatalog.PinyinCode = this.txtPinyinCode.Text.Trim();
            procureCatalog.GoodsName = txtGoodsName.Text.Trim();
            procureCatalog.IsUsing = true;//只有正常状态的产品才能选择配送企业
            procureCatalog.ProjectID = ViewState["ProjectId"].ToString();
            procureCatalog.SortFields = " ProcureCataLogID ";
            GvRelaion.AutoGenerateColumns = false;
            int totalrecord = 0;
            //AspNetPager1.PageSize =1;
            IBLL_ProcurementBasic iDistribution = Factory.BLL_ProcurementBasic();
            this.GvRelaion.DataSource = iDistribution.GetProcureCatalogByWhere(procureCatalog, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalrecord);
            GvRelaion.DataBind();
            AspNetPager1.RecordCount = totalrecord;
        }
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            BangdinGvRelaion();
        }

        /// <summary>
        /// 将给定的url加上script 实现页面跳转
        /// 针对button 的 onclintclick 新窗口打开
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        protected string OpenURLScript(string str)
        {
            int index = str.IndexOf("?");
            //给url加returnUrl,值为当前页面的Url
            if (index != -1)
            {
                str += "&" + Constants.QUERYSTRING_RETURN_URL + "=" + Page.Request.RawUrl;
            }
            else
            {
                str += "?" + Constants.QUERYSTRING_RETURN_URL + "=" + Page.Request.RawUrl;
            }
            string strScript = "if(!this.disabled){window.open('" + str + "');} return false;";
            return strScript;
        }

        protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
        {
            bool temp = false;
            //遍历列表的所有行
            for (int _index = 0; _index < GvRelaion.Rows.Count; _index++)
            {
                CheckBox ckb = ((CheckBox)GvRelaion.Rows[_index].FindControl("checkbox1"));
                if (ckb.Checked)
                {
                    temp = true;
                    break;
                }
            }
            if (temp == false)
            {
                HZ.Web.WebUtil.Alert("请选择配送商品！", this); return;
            }

            string CompanyID_PS = HZ.Fun2.CheckString(Request.QueryString["PID"]);

            IList<SelectRelation> lst = new List<SelectRelation>();

            //遍历列表的所有行
            for (int _index = 0; _index < gvwArea.Rows.Count; _index++)
            {
                CheckBox ckb = ((CheckBox)gvwArea.Rows[_index].FindControl("checkbox1"));
                if (ckb.Checked)
                {
                    string  strAreaID=gvwArea.DataKeys[_index].Value.ToString();
                    //遍历列表的所有行
                    for (int _temp = 0; _temp < GvRelaion.Rows.Count; _temp++)
                    {
                        CheckBox ckb2 = ((CheckBox)GvRelaion.Rows[_temp].FindControl("checkbox1"));
                        if (ckb2.Checked)
                        {
                            SelectRelation srModel = new SelectRelation();

                            srModel.CompanyID_TB = CurrentAccount.GetUser().Org.OrgID;
                            srModel.CompanyID_PS = CompanyID_PS;
                            srModel.AreaID = strAreaID;
                            srModel.ProcureCatalogID = GvRelaion.DataKeys[_temp].Value.ToString();
                            srModel.Status = -1;

                            lst.Add(srModel);
                        }
                    }
                }
            }

            if (lst.Count > 0)
            {
                int[] arrayResult = new int[5]{0,0,0,0,0};

                int result = iSelectRelation.AddSelectRelation(lst, ViewState["ishcygcg"], out arrayResult);
                if (result == 1 && lst.Count == arrayResult[0]
                    && arrayResult[0] == arrayResult[1] + arrayResult[3] + arrayResult[4])
                {
                    //HZ.Web.MessageBox.AlertAndRedirect();
                    //Response.Redirect("CompanyMaintain.aspx");
                    string strConfirm = string.Empty;

                    strConfirm += "共提交 " + arrayResult[0] + " 条；\\n\\r";
                    strConfirm += "成功 " + arrayResult[1] + " 条；\\n\\r";
                    strConfirm += "失败 " + arrayResult[2] + " 条；\\n\\r";
                    strConfirm += "已存在 " + arrayResult[3] + " 条；\\n\\r";
                    strConfirm += "超过五家的 " + arrayResult[4] + " 条；\\n\\r";
                    strConfirm += "是否继续提交？\\n\\r";
                     
                    //信息
                    this.Page.ClientScript.RegisterStartupScript( this.GetType(), "myscript",ConfirmAlertMessage(strConfirm,"smile"), true);
                }
                else
                {
                    HZ.Web.WebUtil.Alert("操作失败！", this); return;
                }

            }
            else
            {
                HZ.Web.WebUtil.Alert("请选择配送商品！", this); return;
            }

        }

        protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
        {
            if (this.Wizard1.ActiveStepIndex == 0)
            {
                bool temp = false;
                //遍历列表的所有行
                for (int _index = 0; _index < gvwArea.Rows.Count; _index++)
                {
                    CheckBox ckb = ((CheckBox)gvwArea.Rows[_index].FindControl("checkbox1"));
                    if (ckb.Checked)
                    {
                        temp = true;
                        break;
                    }
                }
                if (temp == false)
                {
                    this.Wizard1.ActiveStepIndex = 1;
                    this.Wizard1.ActiveStepIndex = 0;

                    HZ.Web.WebUtil.Alert("请选择配送区域！", this); return;
                }
            }
        }
        /// <summary>
        /// 上一步
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Wizard1_PreviousButtonClick(object sender, WizardNavigationEventArgs e)
        {
            this.Wizard1.ActiveStepIndex = 0;
        }

        protected void Wizard1_CancelButtonClick(object sender, EventArgs e)
        {
            Response.Redirect("CompanyMaintain.aspx");
        }

        /// <summary>
        /// 隐藏域变更事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void hidConfirm_ValueChanged(object sender, EventArgs e)
        {
            if (this.hidConfirm.Value.Length > 0)
            {
                Response.Redirect("CompanyMaintain.aspx");
            }
        }

        /// <summary>
        /// Confirm提示信息
        /// </summary>
        /// <param name="strMessage">提示信息</param>
        protected string ConfirmAlertMessage(string message, string index)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("");
            sb.Append("if (confirm('");
            sb.Append(@message);
            sb.Append("')) {");

            sb.Append("document.getElementById('ctl00_ContentPlaceHolder1_hidConfirm').value = '';");
            sb.Append("} else {");

            sb.Append("document.getElementById('ctl00_ContentPlaceHolder1_hidConfirm').value = '");
            sb.Append(index);
            sb.Append("';");
            sb.Append("document.forms[0].submit(); };");
            return sb.ToString();
        }
    }
}
